<!DOCTYPE html>
<html>
<head>
    <title>Upload Image</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            padding: 20px;
        }

        h2 {
            color: #333;
            text-align: center;
        }

        form {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            max-width: 100%;
            margin: 0 auto;
        }

        label {
            display: block;
            margin-bottom: 5px;
        }

        input[type="file"], input[type="text"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            border: 1px solid #ddd;
            box-sizing: border-box;
        }

        input[type="submit"] {
            background-color: #333;
            color: #fff;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }

        input[type="submit"]:hover {
            background-color: #555;
        }

        #preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin: 10px auto;
            border: 2px solid #ddd;
            padding: 10px;
            border-radius: 5px;
        }

        .preview-image {
            width: 100px;
            height: 100px;
            overflow: hidden;
            border: 1px solid #ddd;
            border-radius: 5px;
            position: relative;
        }

        .preview-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
        }

        .error-message {
            color: red;
            margin-top: 5px;
        }

        .progress-container {
            margin-top: 10px;
        }

        .total-progress-bar {
            width: 0%;
            height: 20px;
            background-color: #555;
            text-align: center;
            color: #fff;
            line-height: 20px;
            border-radius: 5px;
            display: none;
        }

        .file-progress-bar {
            width: 0%;
            height: 15px;
            background-color: #888;
            text-align: center;
            color: #000;
            line-height: 15px;
            border-radius: 5px;
            margin-top: 5px;
            display: none;
        }

        /* 遮罩层样式 */
        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .overlay-content {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            text-align: center;
            font-size: 1.2em;
            color: #333;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            form {
                padding: 15px;
            }
            .preview-image {
                width: 50px;
                height: 50px;
            }
            input[type="submit"] {
                padding: 15px 30px;
            }
            .total-progress-bar {
                height: 10px;
                line-height: 10px;
            }
            .file-progress-bar {
                height: 8px;
                line-height: 8px;
            }
        }
    </style>
</head>
<body>
<h2>Upload Image</h2>
<form action="/upload" method="post" enctype="multipart/form-data">
    <label for="image">Image:</label>
    <input type="file" id="image" name="image" accept="image/*" required multiple>
    <div id="preview-container"></div>
    <label for="file_name">File Name:</label>
    <input type="text" id="file_name" name="file_name">
    <label for="description">Description:</label>
    <input type="text" id="description" name="description">
    <input type="submit" value="Upload" id="upload-button">
    <div class="error-message" id="error-message"></div>
    <div class="progress-container">
        <div class="total-progress-bar" id="total-progress-bar"></div>
    </div>
</form>

<!-- 遮罩层 -->
<div class="overlay" id="upload-overlay">
    <div class="overlay-content">
        <p>Uploading...</p>
        <p>Please wait...</p>
    </div>
</div>

<script>
    // Function to read user data from cookies
    function getUserDataFromCookies() {
        const cookies = document.cookie.split('; ');
        const userData = {};
        cookies.forEach(cookie => {
            const [key, value] = cookie.split('=');
            if (key === 'user_id' || key === 'legacy_user_id' || key === 'access_token') {
                userData[key] = decodeURIComponent(value);
            }
        });
        return userData;
    }

    // Function to show error message
    function showError(message) {
        const errorMessage = document.getElementById('error-message');
        errorMessage.innerText = message;
    }

    // Function to hide error message
    function hideError() {
        const errorMessage = document.getElementById('error-message');
        errorMessage.innerText = '';
    }

    // Function to disable upload button
    function disableUploadButton() {
        const uploadButton = document.getElementById('upload-button');
        uploadButton.disabled = true;
        uploadButton.title = 'You are not logged in. Please log in to upload images.';
    }

    // Function to enable upload button
    function enableUploadButton() {
        const uploadButton = document.getElementById('upload-button');
        uploadButton.disabled = false;
        uploadButton.title = '';
    }

    // Check if user is logged in when the page loads
    window.onload = function() {
        const userData = getUserDataFromCookies();
        if (!userData.access_token) {
            showError('You are not logged in. Please log in to upload images.');
            disableUploadButton();
        } else {
            enableUploadButton();
        }
    };

    // Function to handle image preview
    document.getElementById('image').addEventListener('change', function(event) {
        const input = event.target;
        const previewContainer = document.getElementById('preview-container');
        previewContainer.innerHTML = ''; // Clear previous previews

        if (input.files) {
            Array.from(input.files).forEach(file => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const previewDiv = document.createElement('div');
                    previewDiv.className = 'preview-image';

                    const img = document.createElement('img');
                    img.src = e.target.result;

                    previewDiv.appendChild(img);
                    previewContainer.appendChild(previewDiv);
                };
                reader.readAsDataURL(file);
            });
        }
    });

    // Function to handle form submission
    document.querySelector('form').addEventListener('submit', function(event) {
        event.preventDefault();

        // Clear previous error messages
        hideError();

        // Get user data from cookies
        const userData = getUserDataFromCookies();
        if (!userData.user_id) {
            showError('You are not logged in. Please log in to upload images.');
            return;
        }

        // Get form data
        const formData = new FormData(this);
        const files = formData.getAll('image');
        const userDefinedName = document.getElementById('file_name').value.trim();
        const description = document.getElementById('description').value.trim();

        // Check if multiple files are uploaded
        if (files.length > 1) {
            if (userDefinedName || description) {
                showError('Name and description are not allowed for multiple uploads.');
                return;
            }
        }

        // Initialize progress variables
        let totalFiles = files.length;
        let uploadedFiles = 0;

        // Prepare data for upload
        const uploadData = [];
        files.forEach((file, index) => {
            const fileName = file.name;
            const fileData = {
                file: file,
                file_name: fileName,
                name: userDefinedName || '',
                description: description || '',
                user_id: userData.user_id,
                legacy_user_id: userData.legacy_user_id,
                access_token: userData.access_token
            };
            uploadData.push(fileData);
        });

        // Function to update total progress bar
        function updateTotalProgressBar() {
            const progressBar = document.getElementById('total-progress-bar');
            const percentComplete = (uploadedFiles / totalFiles) * 100;
            progressBar.style.width = percentComplete + '%';
            progressBar.textContent = `${uploadedFiles}/${totalFiles} (${Math.round(percentComplete)}%)`;
            if (percentComplete > 0) {
                progressBar.style.display = 'block';
            }
        }

        // Show overlay and disable form
        const uploadOverlay = document.getElementById('upload-overlay');
        uploadOverlay.style.display = 'flex';
        document.querySelector('form').style.pointerEvents = 'none'; // Disable form interaction

        // Upload images
        uploadData.forEach(fileData => {
            const reader = new FileReader();
            const fileProgressBar = document.createElement('div');
            fileProgressBar.className = 'file-progress-bar';
            fileProgressBar.textContent = '0%';
            document.querySelector('.progress-container').appendChild(fileProgressBar);

            reader.onloadstart = function() {
                fileProgressBar.style.display = 'block';
            };

            reader.onprogress = function(event) {
                if (event.lengthComputable) {
                    const percentComplete = (event.loaded / event.total) * 100;
                    fileProgressBar.style.width = percentComplete + '%';
                    fileProgressBar.textContent = Math.round(percentComplete) + '%';
                }
            };

            reader.onload = function() {
                const data = reader.result;

                fetch('https://dshmbsawwrbuycnivcjs.supabase.co/rest/v1/images', {
                    method: 'POST',
                    headers: {
                        'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRzaG1ic2F3d3JidXljbml2Y2pzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTM5Mjg2OTAsImV4cCI6MjA2OTUwNDY5MH0.fwRJD-WuST7mCbJf9h2i2Xk0z6mtCMCeV--JGUecC6A',
                        'Authorization': `Bearer ${fileData.access_token}`,
                        'Content-Type': 'application/json',
                        'Prefer': 'return=minimal'
                    },
                    body: JSON.stringify({
                        file_name: fileData.file_name,
                        name: fileData.name,
                        description: fileData.description,
                        user_id: fileData.user_id,
                        legacy_user_id: fileData.legacy_user_id,
                        data: data
                    })
                })
                    .then(response => {
                        if (response.ok) {
                            uploadedFiles++;
                            updateTotalProgressBar();
                            fileProgressBar.style.display = 'none'; // Hide file progress bar after upload
                        } else {
                            throw new Error('Error: ' + response.statusText);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showError('Failed to upload image. Please check the URL and try again later.');
                        fileProgressBar.style.display = 'none'; // Hide file progress bar on error
                    })
                    .finally(() => {
                        if (uploadedFiles === totalFiles) {
                            // Hide overlay and re-enable form
                            uploadOverlay.style.display = 'none';
                            document.querySelector('form').style.pointerEvents = 'auto';
                        }
                    });
            };

            reader.readAsDataURL(fileData.file);
        });
    });
</script>

<!-- 引入访客统计模块 -->
<script src="../visitor-tracker.js"></script>
<!-- Cloudflare Web Analytics -->
<script defer src='../lib/cloudflare/beacon.min.js' data-cf-beacon='{"token": "0e55e488041949479a3dace73ef940cd"}'>
</script>
<!-- End Cloudflare Web Analytics -->

</body>
</html>